package com.yupi.springbootinit.config;

import com.yupi.springbootinit.exception.CustomRejectedExecutionHandler;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

@Configuration
public class ThreadPoolExecutorConfig {

    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {
        ThreadFactory threadFactory = new ThreadFactory() {
            private int count = 1;

            @Override
            public Thread newThread(@NotNull Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("线程" + count);
                count++;
                return thread;
            }
        };
        // 使用自定义的拒绝策略类
        RejectedExecutionHandler rejectionHandler = new CustomRejectedExecutionHandler();

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2, // 核心线程数
                4, // 最大线程数
                100, TimeUnit.SECONDS, // 线程最大空闲时间
                new ArrayBlockingQueue<>(4), // 有界任务队列
                threadFactory, // 线程工厂
                rejectionHandler // 使用自定义的拒绝策略类
        );
        return threadPoolExecutor;
    }
}